#ifndef __MEANFILTER_H
#define __MEANFILTER_H

template <int Length>
class MeanFilter
{
public:
    /**
      @brief 滤波宽度(1,100)
     */
    MeanFilter()
    {
        static_assert((Length > 0) && (Length < 101), "MedianFilter Length [1,100]");
        for (int x = 0; x < Length; x++)
            buffer_num[x] = 0;
        flag = Length;
        where_num = 0;
        sum = 0;
    }
    ~MeanFilter(){};
    void operator>>(float &num) { num = out(); }
    void operator<<(const float &num) { in(num); }
    float f(float num)
    {
        in(num);
        return (out());
    }

protected:
    void in(float num)
    {
        now_num = num;
        sum -= buffer_num[where_num]; /*<! sum减去旧值 */
        sum += num;                   /*<! sum加上新值 */
        buffer_num[where_num++] = num;
        flag > 0 ? flag-- : 0; /*<!flag=Length然后递减保证宽度内都是有效波值 */
        where_num %= Length;
    }

    float out()
    {
        if (flag > 0)
            return now_num;
        else
            return (sum / Length);
    }

private:
    float buffer_num[Length];
    float now_num;
    float sum; /*<! 宽度和数字和 */
    int flag, where_num;
};
#endif

